var TOKEN_EXIST = 5004;
jQuery.extend(
    {
        TsignAjax: function (postData) {
            var defalut = {
                async: true,
                error: function () {
                    showAlert("系统出错，请稍后再试");
                },
                success: function () {
                },
                data: "edit=" + (new Date()).toString(),
                dataType: "xml",
                err: function (jsonData) {
                    var errShow = new Boolean(jsonData["errShow"]);
                    if (errShow == true) {
                        if(jsonData["errCode"] == TOKEN_EXIST){
                            window.location.href = "./login/login!page?skip=index";
                            return ;
                        }
                        showAlert(jsonData["msg"]);
                    } else {
                        showAlert("系统出错，请稍后重试");
                    }
                    return;
                },
            }
            var opt = $.extend({}, defalut, postData);
            $.ajax({
                url: opt.url,
                type: "POST",
                data: opt.data,
                dataType: opt.dataType,
                async: opt.async,
                timeout: 300000,
                error: opt.error,
                success: function (data) {
                    var result = data;
                    if (opt.dataType == "xml") {
                        result = $(data).find("result >resultMsg").text();
                        if (result == null || result == "") {
                            showAlert("系统出错，请稍后重试");
                            return;
                        }
                    }
                    var jsonData = JSON.parse(result);
                    var errCode = jsonData["errCode"];
                    if (errCode > 0) {
                        opt.err(jsonData);
                    } else {
                        opt.success(jsonData);
                    }
                }
            });
        },
        TsignSubmit: function (postData, flag) {
            var defaultData = {
                target: "_self",
                isSubmit:true,
                formName:"esignsubmit"
            }

            var opt = $.extend({}, defaultData, postData);
            $("#" + opt.formName).remove();
            var appendHtml = "<form id='"+opt.formName+"' name='"+opt.formName+"' action='" + opt.url + "' accept-charset='utf-8' method='post' target='" + opt.target + "' >";
            var arr = opt.input;
            if (!flag) {
                for (var i = 0; i < arr.length; i++) {
                    appendHtml += "<input style='display:none' name='" + arr[i]["name"] + "' value='" + arr[i]["value"] + "'/>";
                }
            } else {
                for (var key in arr) {
                    appendHtml += "<input style='display:none' name='" + key + "' value='" + arr[key] + "'/>";
                }
            }
            appendHtml += "</form>";
            $("body").append(appendHtml);
            if(opt.isSubmit){
                $("#" + opt.formName).submit();
            }
        },
        //弹出模态框
        bootstrapDialog: function (postData) {
            var settings = {
                title: "",
                message: "",
                CustomData: {},
                closable: true,
                buttons:[],
                size:BootstrapDialog.SIZE_NORMAL,
                onshown: function () {
                },
                onshow: function () {
                },
                onhidden:function(){

                },
                onhide:function(){

                }
            }
            var opt = $.extend({}, settings, postData);
            BootstrapDialog.show({
                title: opt.title,
                CustomData: opt.CustomData,
                message: opt.message,
                closable: opt.closable,
                buttons:opt.buttons,
                size:opt.size,
                onshown: function (dialog) {
                    opt.onshown();
                },
                onshow: function (dialog) {
                    opt.onshow();
                },
                onhidden:function(){
                    opt.onhidden();
                },
                onhide:function(){
                    opt.onhide();
                }

            });
        },
        //阻止冒泡
        stopPropagation: function () {
            function getEvent() {
                if (window.event) {
                    return window.event;
                }
                func = getEvent.caller;
                while (func != null) {
                    var arg0 = func.arguments[0];
                    if (arg0) {
                        if ((arg0.constructor == Event || arg0.constructor == MouseEvent
                            || arg0.constructor == KeyboardEvent)
                            || (typeof(arg0) == "object" && arg0.preventDefault
                            && arg0.stopPropagation)) {
                            return arg0;
                        }
                    }
                    func = func.caller;
                }
                return null;
            }

            var e = getEvent();
            if(e!=null){
            	if (window.event) {
            		e.cancelBubble = true;
            	} else if (e.preventDefault) {
            		e.stopPropagation();
            	}
            }
        },


        isIEBrowser: function () {
            var navigatorName = "Microsoft Internet Explorer";
            if ((navigator.userAgent.indexOf('MSIE') > -1 && navigator.userAgent.indexOf('Trident') > -1) ||
                (navigator.userAgent.indexOf('Trident') > -1 && navigator.userAgent.indexOf('rv:11') > -1)) {
                return true;
            }
            return false;

        },
        showAlert : function(msg){
            $.bootstrapDialog({
                title:"信息",
                message:$("<div style='padding: 30px;font-size: 14px'></div>").append(msg),
                size:BootstrapDialog.SIZE_SMALL,
                buttons:[{
                    label:"确定",
                    action:function(dialog){
                        dialog.close();
                    }
                }]
            })
        },
        showFancyUI:function(){
            var appendHtml = "<div class='modal-backdrop fade in' id='TsignFancyBackground' style='text-align: center'>" +
                "</div>";
            $("body").append(appendHtml);
        },
        showLoading:function(){
            var appendHtml = "<div class='modal-backdrop fade in' id='TsignFancyBackground' style='text-align: center'>" +
                "<img src='../../images_2.0/loading.gif' style='position: absolute;top: 50%;margin-top: -64px;margin-left: -64px;'>" +
                "</div>";
            $("body").append(appendHtml);
        },
        closeFancyUI:function(){
            $("#TsignFancyBackground").remove();
        },
        //登陆计费系统
        billingLogin : function(){
            postData = "edit="+(new Date()).toString();
            $.ajax({
                url:'./login/login!billingLogin.xml',
                type:'POST',
                dataType:'xml',
                async:false,
                data:postData,
                success:function(data){
                    var result = $(data).find("result >resultMsg").text();
                    var jsonData = JSON.parse(result);
                    var token = jsonData["token"];
                    var equipId =  jsonData["equipId"];
                    var projectId = jsonData["projectId"];
	                  var projectSecret = jsonData["projectSecret"];
                    var url =  jsonData["url"] +"?"+"token="+token+"&equipId="+equipId+"&edit="+(new Date()).toString();
                    var billingHost = jsonData["billingHost"];
                    var certificateHost = jsonData["certificateHost"];
                    $.ajax({
                        jsonpCallback: 'jsonCallback',
                        cache: false,
                        type: 'GET',
                        async:false,
                        url: url,
                        contentType: "application/json",
                        dataType: 'jsonp',
                        success: function(data){
                            //   var host = '<%=SystemProperties.BILLING_HOST%>'+":"+'<%=SystemProperties.BILLING_PORT%>';
                            var url = billingHost+'/billingsystem/static/js/web-call.js';
                            $.ajax({
                                url: url,
                                async:false,
                                dataType: "script",
                                success: function(){
                                    var obj = createOrderInfoDiv();
                                    obj.appendTo($('.buy'));
                                    getAccountOrderInfo(billingHost);

                                }
                            });
                        },
                        error:  function(){
                        }
                    });

                    // 登录存证
                    var params = {
                        token: token,
                        equipId: equipId,
                        authProjectId: projectId,
                        authProjectSecret: projectSecret
                    };
                    $.ajax({
                        type: 'GET',
                        url: certificateHost + "/evi-web/evidence/v1/login/ssologin",
                        data: params,
                        dataType: "jsonp",
                        contentType: "application/json",
                        jsonpCallback: 'jsonpCallback',
                        success: function (response) {

                        },
                        error: function (error) {

                        }
                    });

                }
            });
        },
        checkCertByType:function(type){
            var flag = false;
            $.TsignAjax({
                url: "./user/account!getAccountInfo2.xml",
               async:false,
                dataType: "json",
                success:function(jsonData){
                    var certs = jsonData.certs;
                    $(certs).each(function(index){
                            if(certs[index]["type"] == type){
                                flag = true;
                                return false;
                            }
                    });
                }
            });
            return flag;
        },
        checkUkeyByIE:function(){
            var flag = true;
            if($.checkCertByType(1) && !$.isIEBrowser()){
                showAlert_notClose("您的账号仅允许通过Ukey签署材料，请切换至IE9及以上的IE浏览器");
               flag =  false;
            }
            return flag;
        },
        getBrowserVersion:function(){
            var browser = function () {
                var agent = navigator.userAgent.toLowerCase(),
                    opera = window.opera,
                    browser = {
                        //检测当前浏览器是否为IE
                        ie: /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
                        //检测当前浏览器是否为Opera
                        opera: (!!opera && opera.version),
                        //检测当前浏览器是否是webkit内核的浏览器
                        webkit: (agent.indexOf(' applewebkit/') > -1),
                        //检测当前浏览器是否是运行在mac平台下
                        mac: (agent.indexOf('macintosh') > -1),
                        //检测当前浏览器是否处于“怪异模式”下
                        quirks: (document.compatMode == 'BackCompat')
                    };
                //检测当前浏览器内核是否是gecko内核
                browser.gecko = (navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
                var version = 0;
                // Internet Explorer 6.0+
                if (browser.ie) {
                    var v1 = agent.match(/(?:msie\s([\w.]+))/);
                    var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
                    if (v1 && v2 && v1[1] && v2[1]) {
                        version = Math.max(v1[1] * 1, v2[1] * 1);
                    } else if (v1 && v1[1]) {
                        version = v1[1] * 1;
                    } else if (v2 && v2[1]) {
                        version = v2[1] * 1;
                    } else {
                        version = 0;
                    }
                    //检测浏览器模式是否为 IE11 兼容模式
                    browser.ie11Compat = document.documentMode == 11;
                    //检测浏览器模式是否为 IE9 兼容模式
                    browser.ie9Compat = document.documentMode == 9;
                    //检测浏览器模式是否为 IE10 兼容模式
                    browser.ie10Compat = document.documentMode == 10;
                    //检测浏览器是否是IE8浏览器
                    browser.ie8 = !!document.documentMode;
                    //检测浏览器模式是否为 IE8 兼容模式
                    browser.ie8Compat = document.documentMode == 8;
                    //检测浏览器模式是否为 IE7 兼容模式
                    browser.ie7Compat = ((version == 7 && !document.documentMode) || document.documentMode == 7);
                    //检测浏览器模式是否为 IE6 模式 或者怪异模式
                    browser.ie6Compat = (version < 7 || browser.quirks);
                    browser.ie9above = version > 8;
                    browser.ie9below = version < 9;
                }
                // Gecko.
                if (browser.gecko) {
                    var geckoRelease = agent.match(/rv:([\d\.]+)/);
                    if (geckoRelease) {
                        geckoRelease = geckoRelease[1].split('.');
                        version = geckoRelease[0] * 10000 + (geckoRelease[1] || 0) * 100 + (geckoRelease[2] || 0) * 1;
                    }
                }
                //检测当前浏览器是否为Chrome, 如果是，则返回Chrome的大版本号
                browser.chrome = +RegExp['\x241'];
                if (/chrome\/(\d+\.\d)/i.test(agent)) {
                }
                //检测当前浏览器是否为Safari, 如果是，则返回Safari的大版本号
                if (/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)) {
                    browser.safari = +(RegExp['\x241'] || RegExp['\x242']);
                }
                // Opera 9.50+
                if (browser.opera)
                    version = parseFloat(opera.version());
                // WebKit 522+ (Safari 3+)
                if (browser.webkit)
                    version = parseFloat(agent.match(/ applewebkit\/(\d+)/)[1]);
                //检测当前浏览器版本号
                browser.version = version;
                return browser;
            }();
            return browser.version;
        },
        outOfBounds:function(){
            function Impl(){}
            Impl.Left = function(inner,outer){
                var innerLeft = $(inner).offset().left;
                var innerWidth = $(inner).width();
                var outerLeft = $(outer).offset().left;
                return innerLeft < outerLeft - innerWidth/2 ? true : false;
            };
            Impl.Right = function(inner,outer){
                var innerLeft = $(inner).offset().left;
                var outerLeft = $(outer).offset().left;
                var innerWidth = $(inner).width()
                var outerWidth = $(outer).width();
                return innerWidth + innerLeft - innerWidth/2 > outerLeft + outerWidth ? true : false;
            };
            Impl.Top = function(inner,outer){
                var innerTop = $(inner).offset().top;
                var innerHeight = $(inner).height();
                var outerTop = $(outer).offset().top;
                return innerTop <outerTop - innerHeight/2 ? true : false;
            };
            Impl.Bottom = function(inner,outer){
                var innerHeight = $(inner).height();
                var outerHeight = $(outer).height();
                var innerTop = $(inner).offset().top;
                var outerTop = $(outer).offset().top;
                return innerTop + innerHeight - innerHeight/2 > outerTop + outerHeight ? true : false;
            };
            return Impl;
        }()
    }
);
jQuery.browser={};(function(){jQuery.browser.msie=false; jQuery.browser.version=0;if(navigator.userAgent.match(/MSIE ([0-9]+)./)){ jQuery.browser.msie=true;jQuery.browser.version=RegExp.$1;}})();
